package com.learn.xiaoha.sqlsession;

import com.learn.xiaoha.sqlsession.factory.SimpleSqlSessionFactory;
import com.learn.xiaoha.sqlsession.utils.JdbcExecute;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * SimpleSqlSession
 *
 * @author: cyx_jay
 * @date: 2021/2/2 14:08
 */
public class SimpleSqlSession implements SqlSession {

    private SimpleSqlSessionFactory simpleSqlSessionFactory;

    private DataSource dataSource;

    private Map<Class,Object> mapperMapper;

    private Connection connection;

    public SimpleSqlSessionFactory getSimpleSqlSessionFactory() {
        return simpleSqlSessionFactory;
    }

    public void setSimpleSqlSessionFactory(SimpleSqlSessionFactory simpleSqlSessionFactory) {
        this.simpleSqlSessionFactory = simpleSqlSessionFactory;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public Map<Class, Object> getMapperMapper() {
        return mapperMapper;
    }

    public void setMapperMapper(Map<Class, Object> mapperMapper) {
        this.mapperMapper = mapperMapper;
    }

    @Override
    public Connection getConnection() {
        return connection;
    }

    public void setConnection(Connection connection) {
        this.connection = connection;
    }

    public SimpleSqlSession(SimpleSqlSessionFactory simpleSqlSessionFactory) {
        this.simpleSqlSessionFactory = simpleSqlSessionFactory;
        this.dataSource = simpleSqlSessionFactory.getDataSource();
        this.mapperMapper = simpleSqlSessionFactory.getMapperMap();
    }

    @Override
    public <T> T getMapper(Class<T> tClass) {
        T mapper = (T) this.mapperMapper.get(tClass);
        return mapper;
    }


    @Override
    public void startTransaction() throws SQLException {
        connection.setAutoCommit(false);
    }

    @Override
    public void rollBack() throws SQLException {
        connection.rollback();
    }

    @Override
    public void commit() throws SQLException {
        connection.commit();
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }
}
